package org.jeecg.modules.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.*;
import lombok.extern.slf4j.Slf4j;
import net.sf.saxon.expr.instruct.ForEach;
import org.jeecg.common.api.diy.ProfessorApi;
import org.jeecg.common.system.api.ISysBaseAPI;

import org.jeecg.modules.entity.DiyProfessorInfo;
import org.jeecg.modules.mapper.DiyProfessorInfoMapper;
import org.jeecg.modules.service.IDiyProfessorInfoService;
import org.jeecg.modules.util.ConstantDiy;
import org.jeecg.modules.util.SplitUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ResourceUtils;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * @Description: 专家信息录入
 * @Author: jeecg-boot
 * @Date: 2020-05-21
 * @Version: V1.0
 */

@Service
@Slf4j
public class DiyProfessorInfoServiceImpl extends ServiceImpl<DiyProfessorInfoMapper, DiyProfessorInfo> implements IDiyProfessorInfoService {
    @Value(value = "${jeecg.path.upload}")
    private String uploadpath;
    @Autowired
    private DiyProfessorInfoMapper diyProfessorInfoMapper;


    @Autowired
    private ISysBaseAPI sysBaseAPI;

    @Autowired
    private ProfessorApi professorApi;

    @Override
    public String getDeclareCategoryName(String id) {
        String name = diyProfessorInfoMapper.selDictNameById(id);
        return name;
    }

    @Override
    public String getDingDinguserid(String id) {
        return diyProfessorInfoMapper.getDingDinguserid(id);
    }

    @Override
    public String selPhone(String id) {
        return diyProfessorInfoMapper.selPhone(id);
    }

    @Override
    public String getDeclareCategoryIdByName(String name) {
        return diyProfessorInfoMapper.selDictIdByName(name);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveByJsonObj(JSONObject obj, String dingUserId) {
        // 获得审批实例
        String process_instance = obj.getString("process_instance");
        System.out.println("process_instance = " + process_instance);
        // 获得表单组件
        JSONObject object = JSON.parseObject(process_instance);
        String form_component_values = object.getString("form_component_values");

        // 获得数组
        JSONArray objects = JSON.parseArray(form_component_values);
        JSONObject jsonObject = null;


        // 初始化专家信息对象

        DiyProfessorInfo diyProfessorInfo = new DiyProfessorInfo();
        diyProfessorInfo.setDingUserId(dingUserId);
        //遍历
        for (int i = 0; i < objects.size(); i++) {
            jsonObject = objects.getJSONObject(i);
            String name = jsonObject.getString("name");
            String value = jsonObject.getString("value");
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            try {

                switch (name) {
                    case ConstantDiy.D_NAME:
                        diyProfessorInfo.setProfessorName(value);
                        break;
                    case ConstantDiy.D_SEX:
                        diyProfessorInfo.setProfessorSex("男".equals(value) ? 1 : 2);
                        break;
                    case ConstantDiy.D_ADDRESS:
                        diyProfessorInfo.setProfessorAddress(value);
                        break;
                    case ConstantDiy.D_BIRTHDAY:
                        Date date = sdf.parse(value);
                        diyProfessorInfo.setProfessorBirthday(date);
                        break;
                    case ConstantDiy.D_SCHOOL:
                        diyProfessorInfo.setProfessorSchool(value);
                        break;
                    case ConstantDiy.D_PHONE:
                        diyProfessorInfo.setProfessorPhone(value);
                        break;
                    case ConstantDiy.D_PROJECT:
                        diyProfessorInfo.setProfessorProjectIntroduce(value);
                        break;
                    case ConstantDiy.D_PHOTO:
                        // 去掉前边的路径
                        String[] split = value.split(ConstantDiy.IMG_URL_FONT);
                        System.out.println(split[1]);
                        // 去掉"和之后的东西
                        String[] split1 = split[1].split("\"");
                        System.out.println(split1[0]);
                        diyProfessorInfo.setProfessorPhoto(split1[0].getBytes());
                        diyProfessorInfo.setProfessorPhotoString(split1[0]);
                        break;
                    case ConstantDiy.D_INFOPHOTO:
                        System.out.println("保存到数据库里的图片是：" + value);
                        // 去掉前边的路径
                        String[] split4 = value.split(ConstantDiy.IMG_URL_FONT);
                        System.out.println(split4[1]);
                        // 去掉"和之后的东西
                        String[] split5 = split4[1].split("\"");
                        diyProfessorInfo.setProfessorInfoPhoto(split5[0].getBytes());
                        diyProfessorInfo.setProfessorInfoPhotoString(split5[0]);
                        break;
                    case ConstantDiy.D_MAJOR:
                        // 把专业转换成id
                        String majorId = professorApi.queryMajorIdByName(value);
                        diyProfessorInfo.setProfessorMajor(majorId);
                        break;
                    case ConstantDiy.D_MAJORDATE:
                        diyProfessorInfo.setProfessorMajorDate(sdf.parse(value));
                        break;
                    case ConstantDiy.D_GRADUATE:
                        diyProfessorInfo.setProfessorGraduateDate(sdf.parse(value));
                        break;
                    case ConstantDiy.D_EDUCATIONBACKGROUND:
                        diyProfessorInfo.setProfessorEducationBackground(value);
                        break;
                    case ConstantDiy.D_DEGREE:
                        diyProfessorInfo.setProfessorDegree(value);
                        break;
                    case ConstantDiy.D_WORKUNIT:
                        diyProfessorInfo.setProfessorWorkUnit(value);
                        break;
                    case ConstantDiy.D_DECLARECATEGORY:
                        // 根据,截取name
                        String[] split2 = value.split(",");
                        String ids = "";

                        for (int j = 0; j < split2.length; j++) {
                            String id = diyProfessorInfoMapper.selDictIdByName(split2[j]);
                            // 字符串连接
                            ids = ids.concat(id);
                            if (j < split2.length - 1) {
                                ids += ",";
                            }
                        }
                        // 把钉钉回调的专家申报类别变成id传入数据库中
                        diyProfessorInfo.setProfessorDeclareCategory(ids);
                        break;
                    case ConstantDiy.D_POSITION:
                        diyProfessorInfo.setProfessorPosition(value);
                        break;
                    case ConstantDiy.D_BEGINWORK:
                        diyProfessorInfo.setProfessorBeginWork(sdf.parse(value));
                        break;
                    case ConstantDiy.D_TITLE:
                        diyProfessorInfo.setProfessorTitle(value);
                        break;
                    case ConstantDiy.D_WORKMAJOR:
                        diyProfessorInfo.setProfessorWorkMajor(value);
                        break;
                    case ConstantDiy.D_IDENTITY:
                        diyProfessorInfo.setProfessorIdentity(value);
                        break;
                    case ConstantDiy.D_HOMEADDRESS:
                        diyProfessorInfo.setProfessorHomeAddress(value);
                        break;
                    case ConstantDiy.D_HEALTH:
                        diyProfessorInfo.setProfessorHealth(value);
                        break;
                    case ConstantDiy.D_OFFICE:
                        diyProfessorInfo.setProfessorOfficeTel(value);
                        break;
                    case ConstantDiy.D_LEADMSG:
                        diyProfessorInfo.setProfessorLeadMsg(value);
                        break;
                        //身份证复印件一张
                    case ConstantDiy.D_ID:
                        String[] split01 = value.split(ConstantDiy.IMG_URL_FONT);
                        String[] split02 = split01[1].split("\"");
                        diyProfessorInfo.setProfessorId(split02[0].getBytes());
                        diyProfessorInfo.setProfessorIdString(split02[0]);
                        break;
                        //个人承若书一张
                    case ConstantDiy.D_COMMITMENT:
                        String[] split03 = value.split(ConstantDiy.IMG_URL_FONT);
                        String[] split04 = split03[1].split("\"");
                        diyProfessorInfo.setProfessorCommitment(split04[0].getBytes());
                        diyProfessorInfo.setProfessorCommitmentString(split04[0]);
                        break;
                        //专业资格职业证书复印件
                    case ConstantDiy.D_QUALIFICATION:
                        String string01= SplitUtil.splitutil(value);
                        System.out.println("专业资格职业证书复印件"+value);
                        diyProfessorInfo.setProfessorQualification(string01.getBytes());
                        diyProfessorInfo.setProfessorQualificationString(string01);
                        break;
                        //个人工作简历
                    case ConstantDiy.D_RESUME:
                        String string02= SplitUtil.splitutil(value);
                        System.out.println("个人工作简历"+value);
                        diyProfessorInfo.setProfessorResume(string02.getBytes());
                        diyProfessorInfo.setProfessorResumeString(string02);
                        break;
                        //学历、学位证书复印件
                    case ConstantDiy.D_DEGREEIMAGE:
                        String string03= SplitUtil.splitutil(value);
                        System.out.println("学历、学位证书复印件"+value);
                        diyProfessorInfo.setProfessorDegreeImage(string03.getBytes());
                        diyProfessorInfo.setProfessorDegreeImageString(string03);
                        break;
                        //其他证明专业能力的材料
                    case ConstantDiy.D_OTHER:
                        String string04= SplitUtil.splitutil(value);
                        System.out.println("其他证明专业能力的材料"+value);
                        diyProfessorInfo.setProfessorOther(string04.getBytes());
                        diyProfessorInfo.setProfessorOtherString(string04);
                        break;
//                    case ConstantDiy.D_APPROVEMSG:
//                        diyProfessorInfo.setProfessorApproveMsg(value);
//                        break;

                    default:
                        break;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        // 获得行政审批意见
        String operation_records = object.getString("operation_records");
        // 获得数组
        JSONArray operation_records_array = JSON.parseArray(operation_records);
        // 遍历数组
        for (int i = 0; i < operation_records_array.size(); i++) {
            // 获取审批意见
            String remark = operation_records_array.getJSONObject(i).getString("remark");
            if (remark != null && !"".equals(remark.trim())) {
                // 把审批意见放入对象中
                diyProfessorInfo.setProfessorApproveMsg(remark);
            }
        }
        diyProfessorInfo.setDelFlag(0);
        DiyProfessorInfo info = diyProfessorInfoMapper.selectInfoByDIngUserId(dingUserId);
        if (info != null) {
            // 执行更新操作
            diyProfessorInfoMapper.deleteDingDinguserid(dingUserId);
            diyProfessorInfoMapper.insert(diyProfessorInfo);
            log.info("专家修改个人信息成功 ==> {} ", diyProfessorInfo);
        } else {
            diyProfessorInfoMapper.insert(diyProfessorInfo);
            log.info("审批专家通过，保存数据库中 ==> {} ", diyProfessorInfo);
        }
    }

    @Override
    public int updateDiyProfessorOneField(String dingUserId, String fieldName, int filedValue) {
        return diyProfessorInfoMapper.updateDiyProfessorOneField(dingUserId, fieldName, filedValue);
    }

    @Override
    public int updateDiyProfessorOneField(String dingUserId, String fieldName, String filedValue) {
        return diyProfessorInfoMapper.updateDiyProfessorOneField(dingUserId, fieldName, filedValue);
    }

    @Override
    public Integer deleteProfessorByDingId(String DingId) {
        log.debug(DingId);
        QueryWrapper<DiyProfessorInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("ding_user_id", DingId);

        return diyProfessorInfoMapper.delete(wrapper);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Integer deleteProfessorByUnionId(String unionId) {
        // 删除user_role表中的数据
        Integer result = sysBaseAPI.delRoleByUsername(unionId);
        log.debug("删除用户角色 ：" + result);
        // 删除user表中的数据
        return diyProfessorInfoMapper.deleteProfessorByUnionId(unionId);
    }

    @Override
    public DiyProfessorInfo queryProfessorInfoByUserId(String userid) {
        QueryWrapper<DiyProfessorInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("ding_user_id", userid);

        return diyProfessorInfoMapper.selectOne(wrapper);
    }

    @Override
    public void updateChangeInfo(String originator_userid) {
        UpdateWrapper<DiyProfessorInfo> wrapper = new UpdateWrapper<>();
        wrapper.set("is_change_info", 1)
                .eq("ding_user_id", originator_userid);
        diyProfessorInfoMapper.update(null, wrapper);
    }

    @Override
    public String exportPDF(List<String> list) {
        InputStream inputStream = this.getClass().getResourceAsStream("/professorInfo.pdf");
        // 模板路径
        String templatePath = "D:\\Git-Pro\\professorInfo.pdf";
        System.out.println("temp =====>"+templatePath);
        // 生成的新文件路径
        String filePath = UUID.randomUUID() +".pdf";
        String newPDFPath = uploadpath+File.separator+ filePath;
        PdfReader reader;
        FileOutputStream out;
        ByteArrayOutputStream bos;
        PdfStamper stamper;
        try {
            out = new FileOutputStream(newPDFPath);// 输出流
            reader = new PdfReader(templatePath);// 读取pdf模板
            bos = new ByteArrayOutputStream();
            stamper = new PdfStamper(reader, bos);
            AcroFields form = stamper.getAcroFields();

            String[] arr = new String[list.size()];
            for (int i = 0; i < arr.length; i++) {
                arr[i] = list.get(i);
            }
            int i = 0;
            java.util.Iterator<String> it = form.getFields().keySet().iterator();
            // 默认12号字体
            float fontSize = 12f;

            // 设置中文字体
            BaseFont baseFont = BaseFont.createFont("STSongStd-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);

            while (it.hasNext()) {
                String name = it.next();
                System.out.println(arr[i]);
                // 文本框宽度
                Rectangle position = form.getFieldPositions(name).get(0).position;
                float textBoxWidth = position.getWidth();
                // 文本框高度
                float textBoxHeight = position.getHeight();
                // 文本单行行高
                float ascent = baseFont.getFontDescriptor(BaseFont.ASCENT,fontSize);
                // baseFont渲染后的文字宽度
                float textWidth = baseFont.getWidthPoint( arr[i], fontSize);

                // 文本框高度只够写一行，并且文字宽度大于文本框宽度，则缩小字体
                if (textBoxHeight <= ascent * 1.6) {
                    while (textWidth >= textBoxWidth) {
                        fontSize--;
                        textWidth = baseFont.getWidthPoint( arr[i], fontSize);
                    }
                }else if(textWidth >= textBoxWidth){
                    while (textWidth >= textBoxWidth) {
                        fontSize--;
                        textWidth = baseFont.getWidthPoint( arr[i], fontSize);
                    }
                }else {
                }
                form.setFieldProperty(name, "textsize", fontSize, null);
                form.setField(name, arr[i++]);
                fontSize=12f;
            }
            // 如果为false那么生成的PDF文件还能编辑，一定要设为true
            stamper.setFormFlattening(true);
            stamper.close();

            Document doc = new Document();
            PdfCopy copy = new PdfCopy(doc, out);
            doc.open();
            PdfImportedPage importPage = copy.getImportedPage(new PdfReader(bos.toByteArray()), 1);
            copy.addPage(importPage);
            doc.close();

        } catch (IOException e) {
            return null;
        } catch (DocumentException e) {
            return null;
        }
        // 成功返回1
        return filePath;
    }

    @Override
    public String getMajorNameById(String value) {
        return diyProfessorInfoMapper.selMajorNameById(value);
    }

    @Override
    public IPage<DiyProfessorInfo> pageByEntity(Page<DiyProfessorInfo> page, DiyProfessorInfo diyProfessorInfo) {
        List<DiyProfessorInfo> list = diyProfessorInfoMapper.pageByEntity();
        list.forEach((info)->{
            info.setProfessorMajor(diyProfessorInfoMapper.selMajorNameById(info.getProfessorMajor()));
        });
        page.setRecords(list);
        return page;
    }

}
